package com.xm.spider;

import lombok.extern.slf4j.Slf4j;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 处理翻译任务
 */
@Slf4j
public class ScraperTask implements Runnable{
    private final int page;
    private final int index;
    private final String text;
    private final ChromeOptions options;

    public ScraperTask(int page, int index, String text, ChromeOptions options) {
        this.page = page;
        this.index = index;
        this.text = text;
        this.options = options;
    }

    @Override
    public void run() {
        ChromeDriver driver = null;
        try {
            Thread.sleep((long) (Math.random()*10));

            driver = new ChromeDriver(options);
            //开始翻译内容
            driver.get("https://fanyi.youdao.com/#/TextTranslate");
            WebDriverWait webDriverWait = new WebDriverWait(driver, Duration.ofSeconds(10));
            webDriverWait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#js_fanyi_input")));
            WebElement inputElement = driver.findElement(By.cssSelector("#js_fanyi_input"));
            //最大字符5000，需要对长文本分组
            inputElement.sendKeys(text);
            new WebDriverWait(driver, Duration.ofSeconds(20)).until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("#js_fanyi_output_resultOutput")));
            //xpath：//*[@id="js_fanyi_output_resultOutput"]
            List<WebElement> elements = driver.findElements(By.xpath("//*[@id=\"js_fanyi_output_resultOutput\"]/child::p"));

            //执行结果拼接
            StringBuilder builder = new StringBuilder();
            if(elements != null && !elements.isEmpty()){
                for (WebElement element : elements) {
                    builder.append(element.getText());
                }

                if(!builder.toString().isEmpty()){
                    //将翻译内容拼接暂存
                    Map<Integer, String> resultMap = SeleniumTrans.resultList.get(page);
                    resultMap.put(index, builder.toString());
                    SeleniumTrans.resultList.add(page, resultMap);
                    log.info("处理结果任务[{}-{}]：{}", page, index, builder.toString());
                }
            }

            Thread.sleep((long) (Math.random()*10));
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if(driver != null){
                driver.quit();
            }
        }
    }
}
